import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../providers/order_provider.dart';
import '../../../utils/g.dart';

class UserAddress extends StatefulWidget {
  const UserAddress({Key? key}) : super(key: key);

  @override
  _UserAddressState createState() => _UserAddressState();
}

class _UserAddressState extends State<UserAddress> {
  Map address = {};

  @override
  Widget build(BuildContext context) {
    address = Provider.of<OrderProvider>(context).address;

    var userInfo = address['real_name'].toString()
                  + ", "+address['phone'].toString();
    var addressInfo = address['province'].toString()
                    + address['city'].toString()
                    + address['district'].toString()
                    + address['detail'].toString();
    var defaultInfo = address['is_default'] == 1 ? '[默认]' : '';

    return Container(
      margin: const EdgeInsets.all(10),
      child: ListTile(
        title: Text(userInfo),
        subtitle: Text(defaultInfo + addressInfo),
        trailing: const Icon(
          Icons.chevron_right,
          size: 24,
          color: Colors.grey
        ),
        onTap: () {
          // 收货地址弹窗
          _getAddressDialog(context);
        }
      ),
    );
  }

  void _getAddressDialog(context) {
    showModalBottomSheet(
      context: context, 
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        )
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext ctx, StateSetter stateSetter) {
            return Column(
              children: [
                _renderAddressList(context, stateSetter),
                _renderAddAddress()
              ],
            );
          }
        );
      }
    );
  }

  Widget _renderAddressList(BuildContext context, StateSetter stateSetter) {
    List addressList = [];
    var address = Provider.of<OrderProvider>(context).address;

    return FutureBuilder(
      future: G.api.address.list(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          var res = snapshot.data as Map;
          if (res['status'] == 200) {
            addressList = res['data'];

            return Container(
              margin: const EdgeInsets.fromLTRB(0, 0, 0, 30),
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                physics: const BouncingScrollPhysics(),
                child: Column(
                  children: [
                    Container(
                      margin: const EdgeInsets.all(20),
                      child: const Center(
                        child: Text(
                          "收货地址",
                          style: TextStyle(
                            fontSize: 24,
                            fontWeight: FontWeight.w600
                          ),
                        )
                      ),
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: addressList.isNotEmpty
                      ?
                      addressList.map<Widget>((item) {
                        return RadioListTile(
                          value: item['id'], 
                          groupValue: address['id'], 
                          onChanged: (dynamic value) {
                            Provider.of<OrderProvider>(context, listen: false).setAddress(item);
                            // 重新计算订单价格
                            Provider.of<OrderProvider>(context, listen: false).setOrderPrice();

                            Navigator.pop(context);
                          },
                          title: Text('收货人：'
                            +item['real_name'].toString()
                            + ", "
                            +item['phone'].toString()),
                          subtitle: Text('地址：'
                            + item['province'].toString()
                            + item['city'].toString()
                            + item['district'].toString()
                            + item['detail'].toString()),
                          selected: address['id'] == item['id'],
                          selectedTileColor: Colors.grey.shade100,
                        );
                      }).toList()
                      : [const Center(child: Text('空空如也~'))],
                    )
                  ],
                ),
              ),
            );
          } else {
            // 报错
            G.error('接口请求失败01');
          }
        } else if (snapshot.hasError) {
          return Center(
            child: Text("${snapshot.error}"),
          );
        }

        return G.loader();
      }
    );
  }

  Widget _renderAddAddress() {
    return Container(
      padding: const EdgeInsets.all(10),
      child: ElevatedButton(
        onPressed: () {
          G.router.navigateTo(context, '/address_add');
        }, 
        child: const Text('新增收货地址'),
        style: ButtonStyle(
          elevation: MaterialStateProperty.all(1),
          shape: MaterialStateProperty.all(
            const StadiumBorder(
              side: BorderSide(
                color: Colors.blueAccent,
                width: 2
              )
            )
          ),
          minimumSize: MaterialStateProperty.all(Size(G.width - 40, 50))
        )
      ),
    );
  }
}